package com.celesea.framework;

import com.alibaba.fastjson.JSON;
import com.celesea.WorkflowApplication;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Map;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * 基础测试类
 *
 * @author jack
 * @Date 2017/5/21 16:10
 */
@SpringBootTest(classes = WorkflowApplication.class)
@RunWith(SpringRunner.class)
@WebAppConfiguration
// 测试之后数据可回滚
@Transactional()
//@ActiveProfiles(profiles = "dev")
public abstract class BaseJUnitIT {
	public static final String FORMAT = "url:%s;====>>>>>result:%s";

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected WebApplicationContext webApplicationContext;

	protected MockMvc mockMvc;

	protected MockHttpSession session;

	protected Validator validator;

	public void initValidator() {

		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		messageSource.setUseCodeAsDefaultMessage(false);
		messageSource.setDefaultEncoding("UTF-8");
		messageSource.setCacheSeconds(60);

		LocalValidatorFactoryBean validatorFactory = new LocalValidatorFactoryBean();
		validatorFactory.setProviderClass(org.hibernate.validator.HibernateValidator.class);
		validatorFactory.setValidationMessageSource(messageSource);
		this.validator = validatorFactory;
	}

	@Before
	public void setupMockMvc() {
		this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
		this.session = new MockHttpSession();
		// 填充授权信息
		// this.session.setAttribute("user", null);
		// 初始化验证器
		initValidator();
	}

	@Before
	public void initDatabase() {
	}

	public String doPost(String api, Object params) throws Exception {
		String json = getJson(params);

		String body = this.mockMvc
				.perform((post(api)).contentType(MediaType.APPLICATION_JSON).content(json).session(session)
						.accept(MediaType.APPLICATION_JSON_UTF8))
				.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
				.andDo(print()).andReturn().getResponse().getContentAsString();

		logger.debug("响应结果：{}", body);
		return body;
	}

	private String getJson(Object params) {
		String json = null;
		if (!(params instanceof String)) {
			json = JSON.toJSONString(params);
		} else {
			json = (String) params;
		}
		return json;
	}

	public String doGet(String api) throws Exception {
		String body = this.mockMvc.perform((get(api)).session(session).accept(MediaType.APPLICATION_JSON_UTF8))
				.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
				.andDo(print()).andReturn().getResponse().getContentAsString();

		logger.debug("响应结果：{}", body);
		return body;
	}

	public String doGet(String api, Map<String, Object> params) throws Exception {
		URI uri = UriComponentsBuilder.fromUriString(api).buildAndExpand(params).encode().toUri();
		return this.doGet(uri.toString());
	}

	public String doPut(String api, Object params) throws Exception {
		String body = this.mockMvc
				.perform((put(api)).contentType(MediaType.APPLICATION_JSON).content(getJson(params)).session(session)
						.accept(MediaType.APPLICATION_JSON_UTF8))
				.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
				.andDo(print()).andReturn().getResponse().getContentAsString();

		logger.debug("响应结果：{}", body);
		return body;
	}

	public String doDelete(String api) throws Exception {
		String body = this.mockMvc.perform((delete(api)).session(session).accept(MediaType.APPLICATION_JSON_UTF8))
				.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
				.andDo(print()).andReturn().getResponse().getContentAsString();

		logger.debug("响应结果：{}", body);
		return body;
	}

//	@SuppressWarnings("unchecked")
//	public Tip<Object> resolveContent(String json) throws IOException {
//		return JSON.parseObject(json, Tip.class);
//	}
}
